/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vicarvision;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 *
 * @author User
 */
public class apiencrypt {

    public static byte[] intToByteArray(int value) {
        return new byte[]{
            (byte) value,
            (byte) (value >>> 8),
            (byte) (value >>> 16),
            (byte) (value >>> 24)};

    }

    public static String convertXMLFileToString(String fileName) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            InputStream inputStream = new FileInputStream(new File(fileName));
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
            StringWriter stw = new StringWriter();
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.transform(new DOMSource(doc), new StreamResult(stw));
            return stw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] encrypt(String filename, String type) throws UnsupportedEncodingException {

        //xml to bytes
        String xml = convertXMLFileToString(filename);
        byte[] xmlbytes = xml.getBytes("UTF-8");

        //type to bytes

        byte[] typebytes = type.getBytes("UTF-8");

        //length of type bytes
        byte[] bytes = intToByteArray(typebytes.length);
        //combine the three byte arrays to make one
        byte[] cmb = new byte[bytes.length + typebytes.length + xmlbytes.length];
        System.arraycopy(bytes, 0, cmb, 0, bytes.length);
        System.arraycopy(typebytes, 0, cmb, bytes.length, typebytes.length);
        System.arraycopy(xmlbytes, 0, cmb, bytes.length + typebytes.length, xmlbytes.length);

        // get the length of cmd + add 4
        int lengte = cmb.length;
        byte[] bytes_cmd = intToByteArray(lengte + 4);
        //combine the arrays
        byte[] one = bytes_cmd;
        byte[] two = cmb;
        byte[] combined = new byte[one.length + two.length];
        System.arraycopy(one, 0, combined, 0, one.length);
        System.arraycopy(two, 0, combined, one.length, two.length);
        return combined;
    }
}
